import 'dart:math';

import 'package:flutter/material.dart';
import '../../res/list_data.dart';
import '../../tool/fly_to_album_animation.dart';

class PictureFlyInPage extends StatefulWidget {
  const PictureFlyInPage({super.key});

  @override
  State<PictureFlyInPage> createState() => _PictureFlyInPageState();
}

class _PictureFlyInPageState extends State<PictureFlyInPage>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  // 用于给每个图片绑定 GlobalKey（必须在 State 里）
  final List<GlobalKey> _itemImageKeys = List.generate(
    listData.length,
    (_) => GlobalKey(),
  );

  // 初始化动画控制器
  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 700),
    );
  }

  // 悬浮相册按钮的 GlobalKey
  final GlobalKey _albumKey = GlobalKey();

  // 底部和右下角按钮参数
  final double albumRight = 20; // 相册按钮距离右边的距离
  final double albumBottom = 150; // 相册按钮距离底部的距离
  late double albumSize = 60; // 相册按钮的大小

  bool _didPrecache = false; // 是否已经预缓存了图片

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (!_didPrecache) {
      // 预缓存 listData 中的图片
      for (var item in listData) {
        precacheImage(NetworkImage(item["imageUrl"]), context);
      }
      _didPrecache = true;
    }
  }

  void _flyImageToAlbum(
    int index, {
    required Offset startOffset,
    required Size startSize,
    VoidCallback? onComplete,
  }) {
    final overlay = Overlay.of(context);
    if (overlay == null) return;

    final RenderBox albumBox =
        _albumKey.currentContext!.findRenderObject() as RenderBox;
    final Offset endOffset = albumBox.localToGlobal(Offset.zero);
    final Size endSize = Size(60, 60);

    late OverlayEntry entry;
    entry = OverlayEntry(
      builder: (_) => _FlyingImage(
        imageUrl: listData[index]["imageUrl"],
        startOffset: startOffset,
        startSize: startSize,
        endOffset: endOffset,
        endSize: endSize,
        onComplete: () {
          entry.remove();
          if (onComplete != null) onComplete();
        },
      ),
    );
    overlay.insert(entry);
  }

  Widget _initListViewData(BuildContext context, int index) {
    final item = listData[index];
    return GestureDetector(
      onTap: () {
        //todo 原有页面上层 弹出预览图片，点击解锁后图标进行缩小，然后进行位移到指定的位置，再消失
        final overlay = Overlay.of(context);
        if (overlay == null) return;
        late OverlayEntry fullScreenEntry;

        fullScreenEntry = OverlayEntry(
          builder: (_) => _FullScreenPreviewWithUnlock(
            imageUrl: listData[index]["imageUrl"],
            albumKey: _albumKey,
            onUnlock: (Offset startOffset, Size startSize) {
              // 1️⃣ 点击解锁后立即移除全屏 Overlay
              if (fullScreenEntry.mounted) fullScreenEntry.remove();

              // 2️⃣ 插入飞行动画 Overlay
              _flyImageToAlbum(
                index,
                startOffset: startOffset,
                startSize: startSize,
                onComplete: () {
                  //悬浮相册按钮实现膨胀一下又回复的效果
                  setState(() {
                    albumSize=80;
                  });
                  Future.delayed(const Duration(milliseconds: 100), () {
                    setState(() {
                      albumSize = 60; // 恢复原始大小
                    });
                  });
                },
              );
            },
          ),
        );

        overlay.insert(fullScreenEntry);
      },
      child: Container(
        margin: const EdgeInsets.all(10),
        height: 150, // 可修改图片容器高度
        child: Row(
          children: [
            ClipRRect(
              key: _itemImageKeys[index],
              borderRadius: BorderRadius.circular(12),
              child: Image.network(item["imageUrl"], fit: BoxFit.cover),
            ),
            const SizedBox(width: 10),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(item["title"], style: const TextStyle(fontSize: 16)),
                  const SizedBox(height: 8),
                  Text(
                    item["description"] ?? "",
                    style: const TextStyle(fontSize: 14, color: Colors.grey),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('图片列表 + 底部悬浮按钮')),
      body: Stack(
        children: [
          // 自实现列表，不用 ListView.builder
          SingleChildScrollView(
            padding: const EdgeInsets.only(bottom: 80),
            child: Column(
              children: List.generate(
                listData.length,
                (index) => _initListViewData(context, index),
              ),
            ),
          ),

          // 右下角悬浮相册按钮
          Positioned(
            bottom: albumBottom,
            right: albumRight,
            child: AnimatedContainer(
              duration: const Duration(milliseconds: 300),
              curve: Curves.decelerate,
              key: _albumKey,
              width: albumSize,
              height: albumSize,
              decoration: BoxDecoration(
                color: Colors.orange,
                borderRadius: BorderRadius.circular(12),
                boxShadow: const [
                  BoxShadow(
                    blurRadius: 6,
                    color: Colors.black26,
                    offset: Offset(0, 3),
                  ),
                ],
              ),
              child: IconButton(
                icon: const Icon(Icons.photo_library, color: Colors.white),
                onPressed: () {},
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _FullScreenPreviewWithUnlock extends StatefulWidget {
  final String imageUrl;
  final GlobalKey albumKey;
  final Function(Offset startOffset, Size startSize) onUnlock;

  const _FullScreenPreviewWithUnlock({
    required this.imageUrl,
    required this.albumKey,
    required this.onUnlock,
  });

  @override
  State<_FullScreenPreviewWithUnlock> createState() =>
      _FullScreenPreviewWithUnlockState();
}

class _FullScreenPreviewWithUnlockState
    extends State<_FullScreenPreviewWithUnlock> {
  final GlobalKey _imageKey = GlobalKey();
  bool _hideBackground = false;

  void _handleUnlock() {
    final RenderBox box =
        _imageKey.currentContext!.findRenderObject() as RenderBox;
    final startOffset = box.localToGlobal(Offset.zero);
    final startSize = box.size;

    setState(() {
      _hideBackground = true; // 隐藏背景，动画阶段只显示图片
    });

    widget.onUnlock(startOffset, startSize);
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(color: _hideBackground ? Colors.transparent : Colors.black87),
        Center(
          child: Image.network(
            widget.imageUrl,
            key: _imageKey,
            fit: BoxFit.contain,
          ),
        ),
        Positioned(
          bottom: 50,
          left: 50,
          right: 50,
          child: ElevatedButton(
            onPressed: _handleUnlock,
            child: const Text("解锁"),
          ),
        ),
      ],
    );
  }
}

class _FlyingImage extends StatefulWidget {
  final String imageUrl;
  final Offset startOffset;
  final Offset endOffset;
  final Size startSize;
  final Size endSize;
  final VoidCallback onComplete;

  const _FlyingImage({
    super.key,
    required this.imageUrl,
    required this.startOffset,
    required this.endOffset,
    required this.startSize,
    required this.endSize,
    required this.onComplete,
  });

  @override
  State<_FlyingImage> createState() => _FlyingImageState();
}

class _FlyingImageState extends State<_FlyingImage>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;
  late final Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller =
        AnimationController(
          vsync: this,
          duration: const Duration(milliseconds: 600),
        )..addStatusListener((status) {
          if (status == AnimationStatus.completed) {
            widget.onComplete();
          }
        });
    _animation = CurvedAnimation(parent: _controller, curve: Curves.linear);
    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      builder: (context, child) {
        var _limitSize = 150;
        const double minSize = 150.0;
        final value = _animation.value;
        var newoffset = Offset(
          widget.endOffset.dx - _limitSize,
          widget.endOffset.dy - _limitSize,
        );
        final offset = Offset.lerp(widget.startOffset, newoffset, value)!;
        var scale = 1 - value * 1;
        //缩放比例和原图计算处缩放后图片大小，如果小于150就设置为150
        final widthf = max(_limitSize, widget.startSize.width * scale);
        final heightf = max(_limitSize, widget.startSize.height * scale);
        if (widthf < _limitSize || heightf < _limitSize) {
          //重置缩放比例
          //如果是宽度小于150，则缩放比例设置为150/宽度；否则设置为150/高度
          scale = widthf < heightf ? _limitSize / widthf : _limitSize / heightf;
        }
        return Positioned(
          left: offset.dx,
          top: offset.dy,
          child: Opacity(
            opacity: scale,
            child: SizedBox(
              width: max(widthf, minSize).toDouble(),
              height: max(heightf, minSize).toDouble(),
              child: Image.network(widget.imageUrl, fit: BoxFit.cover),
            ),
          ),
        );
      },
    );
  }
}
